import { requestGet, requestPost } from '@/utils/request/request.ts';
import { onMounted, reactive, ref } from 'vue';
import { Code, LoginForm } from '@/types/user/UserTypes.ts';
import { message } from '@/components/lib/message';
import { JSEncrypt } from 'jsencrypt';
import { user } from '@/store/common/user.ts';
import { auth } from '@/store/common/auth.ts';
import { UserInfo } from '@/types/common/setting.ts';
import { useRoute, useRouter } from 'vue-router';
// 密钥对生成 http://web.chacuo.net/netrsakeypair

const publicKey: string =
  'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCXrZQnkFGUTFi2KqYFWk9u6IiTTCsf4cstid+KaQXNxue7dHXgv3d5/Q3AeFotLYUNZq1CDzax01xGTLcjHVc2ku2krrbpm5U3fu7XwlH4Za9oosc+f7AYlxeTSBPVHG3IBwwZbVP8HAgc9LSWDOxQanA6PAK2ldH9QEBLaGKl+QIDAQAB';

const userManager = user();
const tokenManager = auth();
/**
 * 用户登录相关操作
 */
export function userLogin() {
  const router = useRouter();
  const route = useRoute();
  // 按钮加载状态
  const loading = ref<boolean>(false);
  //初始化验证码信息
  const code = reactive<Code>({
    uuid: '',
    img: '',
  });
  onMounted(() => {
    initCode().then();
  });

  // 验证码查询
  const initCode = async () => {
    await requestGet({
      url: '/auth/code',
    })
      .then((res: any) => {
        code.uuid = res.uuid;
        code.img = res.img;
      })
      .catch(() => {
        code.uuid = '';
        code.img = '';
      });
  };

  /**
   * 用户登录
   * @param userInfo
   * @param codeVal
   */
  const customLogin = async (userInfo: LoginForm, codeVal: Code) => {
    loading.value = true;
    let password: string = '';
    let username: string = '';
    let code: string = '';
    if (userInfo.password !== undefined && userInfo.password !== '') {
      password = encrypt(userInfo.password);
    } else {
      message({ msg: '请输入您的登录密码，登录密码不能为空！', theme: 'error', close: true });
    }
    if (userInfo.username !== undefined && userInfo.username !== '') {
      username = userInfo.username;
    } else {
      message({ msg: '请输入您的登录账号，登录账号不能为空！', theme: 'error', close: true });
    }
    if (userInfo.code !== undefined && userInfo.code !== '') {
      code = userInfo.code;
    } else {
      message({ msg: '请输入验证码', theme: 'error', close: true });
    }
    await requestPost({
      url: '/auth/login',
      data: {
        username: username,
        code: code,
        uuid: codeVal.uuid,
        password: password,
      },
    })
      .then((res: any) => {
        // 设置token,用户基本信息等
        const data = res.user.user;
        const users = (): UserInfo => {
          return {
            username: data.username,
            nickName: data.nickName,
            avatarPath: data.avatarPath,
          };
        };
        // 设置用户基本信息
        userManager.updateUser(users());
        tokenManager.updateToken(res.token);
        // 执行登录跳转
        // 获取重定向地址
        const redirect: any = route.query.redirect;
        if (redirect !== undefined && redirect !== null && redirect !== '') {
          router.push(redirect);
        } else {
          router.push('/');
        }
      })
      .catch((error) => {
        message({ msg: error.msg, theme: 'error', close: true });
        initCode();
      });
  };

  // 加密
  const encrypt = (txt: string): string => {
    const encryptor = new JSEncrypt();
    encryptor.setPublicKey(publicKey); // 设置公钥
    const value: string | false = encryptor.encrypt(txt);
    return value === false ? '' : value; // 对需要加密的数据进行加密
  };
  return {
    code,
    loading,
    customLogin,
    initCode,
  };
}
